/**
 * 压缩图片方法
 * @param file，文件
 * @param obj   图片处理的参数
 * @param callback，回调函数
 */
function photoCompress(file, obj={}, callback) {
    console.log(file,'文件');
    var ready = new FileReader();
    obj.filename=file.name;
    // obj.filename=
    ready.readAsDataURL(file);
    ready.onload = function () {
        var path = this.result;
        canvasDataURL(path, obj, callback, file.size)
    }
}

/**
 * 将base64转回file
 *
 */


/**
 * 将图片在canvas上面进行绘制
 * @param path  图片生成的路径
 * @param obj 图片的质量
 * @param callback 转化完成的回调函数
 */
function canvasDataURL(path, obj, callback, fileSize) {
    var img = new Image();
    img.src = path;
    img.onload = function () {
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);
        var quality = fileSize>1024*1024 ? 1024*1024/fileSize:1;  // 图片控制在1M范围内
      console.log(quality,'质量');
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);

        // 在canvas绘制前填充白色背景
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.drawImage(that, 0, 0, w, h);

        // 图像质量
        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
        }
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality);
        // 回调函数返回base64的值
        base64ToFile(base64, obj.filename, callback)
    }
}

/**
 * 将base 64的转化为文件
 * @param dataurl
 * @param filename
 * @param callback
 */
function base64ToFile(dataurl, filename, callback) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while ((n -= 1) >= 0) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    callback(new File([u8arr], filename, {type: mime}));
}